package com.niit.musicserve.controller;

import com.alibaba.fastjson.JSONObject;
import com.niit.musicserve.annotation.RequireRole;
import com.niit.musicserve.entity.Rank;
import com.niit.musicserve.service.RankService;
import com.niit.musicserve.utils.Const;
import com.niit.musicserve.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/rank")
public class RankController {
	
	@Autowired
	public RankService rankService;
	
	/**
	 * 添加榜单
	 * @param rank 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	@RequireRole("admin")
	public Result<String> addRank(@RequestBody Rank rank){
		
		try{
			if(rank.getRankTitle() == null || rank.getRankTitle().trim().isEmpty()){
				return Result.error("榜单名称不能为空");
			}
			
			if(rank.getRankIntro() == null || rank.getRankIntro().trim().isEmpty()){
				return Result.error("榜单介绍不能为空");
			}
			
			rank.setRankTitle(rank.getRankTitle().trim());
			rank.setRankIntro(rank.getRankIntro().trim());
			
			int result = rankService.insertRank(rank);
			
			if (result > 0){
				
				return Result.success("添加成功",null);
			}
			
			return Result.error("添加失败");
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("服务器错误: " + e.getMessage());
		}
		
		
		
		
	}
	
	/**
	 * 删除榜单
	 * @param request 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/delete",method = RequestMethod.GET)
	@RequireRole("admin")
	public Result<String> deleteRank(HttpServletRequest request){
		
		try{
			String rankId = request.getParameter("rankId");
			
			if (rankId == null || rankId.trim().isEmpty()){
				return Result.error("榜单ID为空");
			}
			
			rankId = rankId.trim();
			
			int flag = rankService.deleteRankById(Integer.parseInt(rankId));
			
			if (flag > 0){
				return Result.success("删除成功",null);
			}
			
			return Result.error("删除失败");
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("服务器错误: " + e.getMessage());
		}
		
		
	}
	
	/**
	 * 修改榜单
	 * @param rank 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/update",method = RequestMethod.POST)
	@RequireRole("admin")
	public Result<String> updateRank(@RequestBody Rank rank){
		
		try{
			if(rank.getRankId() == null){
				return Result.error("榜单ID为空");
			}
			
			if(rank.getRankTitle() == null)
			{
				return Result.error("榜单名称不能为空");
			}

			rank.setRankId(rank.getRankId());
			rank.setRankTitle(rank.getRankTitle());
			rank.setRankIntro(rank.getRankIntro());
			
			int flag = rankService.updateRankById(rank);
			
			if ( flag > 0){
				
				return Result.success("修改成功",null);
			}
			
			return Result.error("修改失败");
		}
		catch (Exception e) {
			e.printStackTrace();
			return Result.error("服务器错误: " + e.getMessage());
		}
	}
	
	/**
	 * 查询所有榜单
	 * @return 响应结果
	 */
	@RequestMapping(value = "/allRank",method = RequestMethod.GET)
	public Result<List<Rank>> allRank(){
		
		return Result.success(rankService.allRank());
	}
	
	@RequestMapping(value = "/list",method = RequestMethod.GET)
	public Result<JSONObject> listRanks(
		@RequestParam(defaultValue = "1") Integer pageNum,
		@RequestParam(defaultValue = "10") Integer pageSize,
		@RequestParam(required = false) String rankTitle) {
		
		try {
			List<Rank> allRanks;
			
			if(rankTitle != null){
				allRanks = rankService.likeRankOfTitle(rankTitle);
			} else {
				allRanks = rankService.allRank();
			}
			
			int total = allRanks.size();
			int startIndex = (pageNum - 1) * pageSize;
			int endIndex = Math.min(startIndex + pageSize, total);
			
			List<Rank> pageRanks = allRanks.subList(startIndex, endIndex);
			
			JSONObject result = new JSONObject();
			result.put("list", pageRanks);
			result.put("total", total);
			result.put("pageNum", pageNum);
			result.put("pageSize", pageSize);
			result.put("pages", (int) Math.ceil((double) total / pageSize));
			
			return Result.success("查询成功", result);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error("服务器错误: " + e.getMessage());
		}
	}
	
	/**
	 * 根据id查询榜单
	 * @param request 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/rankOfId",method = RequestMethod.GET)
	public Result<Rank> rankOfId(HttpServletRequest request){
		String rankId = request.getParameter("rankId");
		
		if(rankId == null){
			return Result.error("参数错误: 榜单ID为空");
		}
		
		rankId = rankId.trim();
		return Result.success(rankService.selectRankById(Integer.parseInt(rankId)));
	}
	
	/**
	 * 根据标题查询榜单
	 * @param request 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/rankOfTitle",method = RequestMethod.GET)
	public Result<List<Rank>> rankOfTitle(HttpServletRequest request){
		String rankTitle = request.getParameter("rankTitle");
		
		if(rankTitle == null){
			return Result.error("参数错误: 榜单标题为空!");
		}
		
		rankTitle = rankTitle.trim();
		
		return Result.success(rankService.rankOfTitle(rankTitle));
	}
	
	/**
	 * 根据标题模糊查询榜单
	 * @param request 前端数据
	 * @return 响应结果
	 */
	@RequestMapping(value = "/likeRankOfTitle",method = RequestMethod.GET)
	public Result<List<Rank>> likeRankOfTitle(HttpServletRequest request){
		String rankTitle = request.getParameter("rankTitle");
		
		if(rankTitle == null){
			return Result.error("参数错误: 榜单标题为空");
		}
		
		rankTitle = rankTitle.trim();
		
		return Result.success(rankService.likeRankOfTitle(rankTitle));
	}
	
	/**
	 * 上传榜单图片
	 * @param avatarFile 前端数据
	 * @param rankId 榜单id
	 * @return 响应结果
	 */
	@RequestMapping(value = "/rankOfPic",method = RequestMethod.POST)
	@RequireRole("admin")
	public Result<String> updateRankPic(
		@RequestParam("file") MultipartFile avatarFile,
		@RequestParam("id") int rankId){
		
		//判断文件是否为空
		if(avatarFile.isEmpty()){
			
			return Result.error("上传失败");
		}
		
		//设置保存到后端的文件名，为了避免重复和前端的引用和与访问，这里的文件名统一设置为当前时间+原文件名
		String fileName = System.currentTimeMillis() + avatarFile.getOriginalFilename();
		
		//设置文件的保存路径
		String filePath = System.getProperty("user.dir") + "/res/img/rankPic";
		
		//根据路径判空，空则创建
		File file1 = new File(filePath);
		if (!file1.exists()){
			file1.mkdirs();
		}
		//设置被保存的地址，一遍下面进行文件的传输
		File dest = new File(filePath + System.getProperty("file.separator") + fileName);
		
		//设置文件保存到数据库的路径
		String storeAvatarPath = "img/rankPic/" + fileName;
		
		try{
			//传输文件到指定地址
			avatarFile.transferTo(dest);
			
			//调用对应方法，将数据库的图片路径更新
			Rank rank = new Rank();
			rank.setRankId(rankId);
			rank.setRankPic(storeAvatarPath);
			int flag = rankService.updateRankById(rank);
			if (flag > 0){
				
				return Result.success("上传成功",null);
			}
			
			return Result.error("上传失败");
		}
		catch (IOException e) {
			
			return Result.error("上传失败" + e.getMessage());
		}
	}
	
	/**
	 * 获取榜单数量
	 * @return 响应结果
	 */
	@RequestMapping(value = "/numberOfRank",method = RequestMethod.GET)
	public Result<Integer> numberOfRank(){
		return Result.success(rankService.numberOfRank());
	}
}
